<template>
  <div class="product-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" @click="$router.push('/admin/productadd')">添加商品</el-button>
        </div>
      </template>

      <el-table :data="productList" v-loading="loading">
        <el-table-column label="商品名称" min-width="300">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-image
                :src="row.picture"
                style="width: 80px; height: 80px; margin-right: 10px"
                fit="cover"
              />
              <div>{{ row.name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="商品描述" min-width="200" />
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            <span>¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="销量" width="100" />
        <el-table-column label="折扣" width="100">
          <template #default="{ row }">
            <span>{{ row.discount }}折</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <span>共 {{ total }} 条</span>
        <el-select v-model="pageSize" class="mx-2" @change="handleSizeChange">
          <el-option
            v-for="item in [15, 30, 50, 100]"
            :key="item"
            :label="`${item}条/页`"
            :value="item"
          />
        </el-select>
        <el-pagination
          v-model:current-page="currentPage"
          :total="total"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProductListAPI } from '@/apis/admin'
import { useRouter } from 'vue-router'

const router = useRouter()

const loading = ref(false)
const productList = ref([]) // 当前页显示的数据
const allProducts = ref([]) // 存储后端返回的所有数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(15) // 每页显示条数
const total = ref(0) // 总条数

// 获取商品列表
const getProductData = async () => {
  loading.value = true
  try {
    const res = await getProductListAPI()
    if (res.code === 0) {
      allProducts.value = res.data // 保存所有数据
      total.value = res.data.length
      // 计算当前页的数据
      updatePageData()
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 更新当前页数据
const updatePageData = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  // 从所有数据中截取当前页需要显示的数据
  productList.value = allProducts.value.slice(startIndex, endIndex)
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  updatePageData() // 只需更新页面数据
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置为第一页
  updatePageData() // 更新页面数据
}

// 编辑商品
const handleEdit = (row) => {
  router.push(`/admin/productedit/${row.id}`)
}

// 删除商品
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确认删除该商品吗？', '提示', {
      type: 'warning'
    })
    // 调用删除API
    ElMessage.success('删除成功')
    getProductData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  getProductData()
})
</script>

<style scoped lang="scss">
.product-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container .el-select {
  width: 80px;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #fd715d;
}

:deep(.el-select-dropdown__item) {
  text-align: center;
  padding: 0 10px;
}
</style>
